<?php

namespace App\Service\SiteLocation;

use App\Models\Kms\User\KmsUser;
use App\Models\Wanggui\CustomerDepartmentDevelopmentManagerModel;
use App\Models\Wanggui\CustomerDepartmentFollowUpRecordModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\BaseService;
use Carbon\Carbon;

class DevelopmentMangerService extends BaseService
{
    public static function overview()
    {
        $managerCount        = 0;
        $taskCount           = 0;
        $effectiveClueCount  = 0;
        $effectiveHouseCount = 0;
        $siteLocationCount   = 0;

        CustomerDepartmentDevelopmentManagerModel::query()
            ->chunkById(20, function ($managers) use (&$managerCount, &$taskCount, &$effectiveClueCount, &$effectiveHouseCount, &$siteLocationCount) {
                foreach ($managers as $manager) {
                    $managerCount++;
                    $taskCount           += $manager->taskCount;
                    $effectiveClueCount  += $manager->effectiveClueCount;
                    $effectiveHouseCount += $manager->effectiveHouseCount;
                    $siteLocationCount   += $manager->siteLocationCount;
                }
            });


        return [
            [
                'text'  => '开发经理',
                'count' => $managerCount
            ],
            [
                'text'  => '任务量',
                'count' => $taskCount
            ],
            [
                'text'  => '有效线索',
                'count' => $effectiveClueCount
            ],
            [
                'text'  => '有效房源',
                'count' => $effectiveHouseCount
            ],
            [
                'text'  => '确址数',
                'count' => $siteLocationCount
            ]
        ];
    }


    /**
     * 列表
     * @param int $pageNum
     * @param int $pageSize
     * @param int $provinceCode
     * @param int $cityCode
     * @param int $districtCode
     * @param string $isResigned
     * @param string $phone
     * @param string $userId
     * @param string $sort
     * @param string $followUpStartTime
     * @param string $followUpEndTime
     * @param string $onTheJobStartTime
     * @param string $onTheJobEndTime
     * @param int $rmsUserId
     * @param string $sortField
     * @param string $sortOrder
     * @return array
     */
    public static function list(int $pageNum, int $pageSize, int $provinceCode, int $cityCode, int $districtCode, string $isResigned, string $phone, string $userId, string $sort, string $followUpStartTime, string $followUpEndTime, string $onTheJobStartTime, string $onTheJobEndTime, int $rmsUserId, string $sortField, string $sortOrder): array
    {
        $paginator = CustomerDepartmentDevelopmentManagerModel::query()
            ->when(mb_strlen($isResigned), function ($query) use ($isResigned) {
                $query->where('isResigned', $isResigned);
            })
            ->when(mb_strlen($phone), function ($query) use ($phone) {
                $query->where('phone', $phone);
            })
            ->when(mb_strlen($userId), function ($query) use ($userId) {
                $query->where('rmsUserId', $userId);
            })
            ->when($cityCode, function ($query) use ($cityCode) {
                $query->whereRaw("rmsUserId in (select assignId from customer_department_task where assignId > 0 and cityCode = {$cityCode})");
            })
            ->when($provinceCode, function ($query) use ($provinceCode) {
                $query->whereRaw("rmsUserId in (select assignId from customer_department_task where assignId > 0 and provinceCode = {$provinceCode})");
            })
            ->when(mb_strlen($sortOrder), function ($query) use ($sortOrder, $sortField) {
                $orderMethod = $sortOrder === 'ascend' ? 'orderBy' : 'orderByDesc';

                // 排序关联字段映射
                $sortFieldMapping = [
                    'taskCount'        => 'taskCount',
                    'validClueCount'   => 'effectiveClueCount',
                    'validHouseCount'  => 'effectiveHouseCount',
                    'siteCount'        => 'siteLocationCount',
                    'joinTime'         => 'onTheJobTime',
                    'lastFollowUpTime' => 'followUpTime',
                    'sCount'           => 'sTaskCount',
                    'aCount'           => 'aTaskCount',
                    'bCount'           => 'bTaskCount',
                    'cCount'           => 'cTaskCount',
                    'sRatio'           => 'sTaskRatio',
                    'aRatio'           => 'aTaskRatio',
                    'bRatio'           => 'bTaskRatio',
                    'cRatio'           => 'cTaskRatio',
                    'saCount'          => 'saTaskCount',
                    'saRatio'          => 'saTaskRatio',
                ];

                if (isset($sortFieldMapping[$sortField])) {
                    $query->$orderMethod($sortFieldMapping[$sortField]);
                }
            })
            ->when(!mb_strlen($sortOrder), function ($query) {
                $query->orderByDesc('followUpTime');
            })
            ->when(mb_strlen($followUpStartTime) && mb_strlen($followUpEndTime), function ($query) use ($followUpStartTime, $followUpEndTime) {
                $query->whereBetween('followUpTime', [Carbon::createFromDate($followUpStartTime)->timestamp, Carbon::createFromDate($followUpEndTime)->endOfDay()->timestamp]);
            })
            ->when(mb_strlen($onTheJobStartTime) && mb_strlen($onTheJobEndTime), function ($query) use ($onTheJobStartTime, $onTheJobEndTime) {
                $query->whereBetween('onTheJobTime', [Carbon::createFromDate($onTheJobStartTime)->timestamp, Carbon::createFromDate($onTheJobEndTime)->endOfDay()->timestamp]);
            })
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);


        $list = $paginator->map(function ($item) {
            return [
                'userId'           => $item->rmsUserId,
                'isResigned'       => $item->isResigned,
                'isResignedStr'    => CustomerDepartmentDevelopmentManagerModel::IS_RESIGNED_MAPPING[$item->isResigned] ?? '',
                'regionPosition'   => $item->taskDistrict,
                'city'             => $item->taskCity,
                'name'             => $item->name,
                'phone'            => $item->phone,
                'taskCount'        => $item->taskCount,
                'sCount'           => $item->sTaskCount,
                'aCount'           => $item->aTaskCount,
                'bCount'           => $item->bTaskCount,
                'cCount'           => $item->cTaskCount,
                'saCount'          => $item->saTaskCount,
                'sRatio'           => $item->sTaskRatio . '%',
                'aRatio'           => $item->aTaskRatio . '%',
                'bRatio'           => $item->bTaskRatio . '%',
                'cRatio'           => $item->cTaskRatio . '%',
                'saRatio'          => $item->saTaskRatio . '%',
                'validClueCount'   => $item->effectiveClueCount,
                'validHouseCount'  => $item->effectiveHouseCount,
                'siteCount'        => $item->siteLocationCount,
                'joinTime'         => Carbon::createFromTimestamp($item->onTheJobTime)->toDateString(),
                'lastFollowUpTime' => $item->followUpTime ? Carbon::createFromTimestamp($item->followUpTime)->toDateTimeString() : '-',
            ];
        });

        return [
            'count'    => $paginator->total(),
            'list'     => $list,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }


    /**
     * 夸父开发经理基本详情
     * @param int $userId
     * @return array
     */
    public static function baseDetail(int $userId): array
    {
        $managerInfoModel = CustomerDepartmentDevelopmentManagerModel::query()
            ->where('rmsUserId', $userId)
            ->first();

        if (null == $managerInfoModel) {
            self::throwErr('没有当前开发经理', 404);
        }

        $taskModel = CustomerDepartmentTaskModel::query()
            ->where('assignId', $userId)
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE, CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM]);


        $sEffectiveClueCount  = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_S)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count();
        $aEffectiveClueCount  = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_A)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count();
        $bEffectiveClueCount  = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_B)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE)->count();
        $sEffectiveHouseCount = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_S)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();
        $aEffectiveHouseCount = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_A)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();
        $bEffectiveHouseCount = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_B)->where('projectPhase', CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE)->count();
        $sSiteLocationCount   = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_S)->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])->count();
        $aSiteLocationCount   = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_A)->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])->count();
        $bSiteLocationCount   = (clone $taskModel)->where('grade', CustomerDepartmentTaskModel::GRADE_B)->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION, CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])->count();


        return [
            'userId'         => $managerInfoModel->rmsUserId,
            'isResigned'     => $managerInfoModel->isResigned,
            'isResignedStr'  => KmsUser::IS_RESIGNED_MAPPING[$managerInfoModel->isResigned] ?? '',
            'regionPosition' => $managerInfoModel->taskDistrict,
            'city'           => $managerInfoModel->taskCity,
            'name'           => $managerInfoModel->name,
            'phone'          => $managerInfoModel->phone,
            'joinTime'       => Carbon::createFromTimestamp($managerInfoModel->onTheJobTime)->toDateString(),
            'taskInfo'       => [
                [
                    'text'     => '任务数量',
                    'count'    => $managerInfoModel->taskCount,
                    'children' => [
                        [
                            'text'  => 'S级',
                            'count' => $managerInfoModel->sTaskCount,
                            'radio' => $managerInfoModel->sTaskRatio . '%'
                        ],
                        [
                            'text'  => 'A级',
                            'count' => $managerInfoModel->aTaskCount,
                            'radio' => $managerInfoModel->aTaskRatio . '%'
                        ],
                        [
                            'text'  => 'B级',
                            'count' => $managerInfoModel->bTaskCount,
                            'radio' => $managerInfoModel->bTaskRatio . '%'
                        ],
                    ]
                ],
                [
                    'text'     => '有效线索',
                    'count'    => $managerInfoModel->effectiveClueCount,
                    'children' => [
                        [
                            'text'  => 'S级',
                            'count' => $sEffectiveClueCount,
                            'radio' => ($managerInfoModel->effectiveClueCount ? (int)($sEffectiveClueCount / $managerInfoModel->effectiveClueCount * 100) : 0) . '%',
                        ],
                        [
                            'text'  => 'A级',
                            'count' => $aEffectiveClueCount,
                            'radio' => ($managerInfoModel->effectiveClueCount ? (int)($aEffectiveClueCount / $managerInfoModel->effectiveClueCount * 100) : 0) . '%',
                        ],
                        [
                            'text'  => 'B级',
                            'count' => $bEffectiveClueCount,
                            'radio' => ($managerInfoModel->effectiveClueCount ? (int)($bEffectiveClueCount / $managerInfoModel->effectiveClueCount * 100) : 0) . '%',
                        ],
                    ]
                ],
                [
                    'text'     => '有效房源',
                    'count'    => $managerInfoModel->effectiveHouseCount,
                    'children' => [
                        [
                            'text'  => 'S级',
                            'count' => $sEffectiveHouseCount,
                            'radio' => ($managerInfoModel->effectiveHouseCount ? (int)($sEffectiveHouseCount / $managerInfoModel->effectiveHouseCount * 100) : 0) . '%',
                        ],
                        [
                            'text'  => 'A级',
                            'count' => $aEffectiveHouseCount,
                            'radio' => ($managerInfoModel->effectiveHouseCount ? (int)($aEffectiveHouseCount / $managerInfoModel->effectiveHouseCount * 100) : 0) . '%',
                        ],
                        [
                            'text'  => 'B级',
                            'count' => $bEffectiveHouseCount,
                            'radio' => ($managerInfoModel->effectiveHouseCount ? (int)($bEffectiveHouseCount / $managerInfoModel->effectiveHouseCount * 100) : 0) . '%',
                        ],
                    ]
                ],
                [
                    'text'     => '确址数量',
                    'count'    => $managerInfoModel->siteLocationCount,
                    'children' => [
                        [
                            'text'  => 'S级',
                            'count' => $sSiteLocationCount,
                            'radio' => ($managerInfoModel->siteLocationCount ? (int)($sSiteLocationCount / $managerInfoModel->siteLocationCount * 100) : 0) . '%',
                        ],
                        [
                            'text'  => 'A级',
                            'count' => $aSiteLocationCount,
                            'radio' => ($managerInfoModel->siteLocationCount ? (int)($aSiteLocationCount / $managerInfoModel->siteLocationCount * 100) : 0) . '%',
                        ],
                        [
                            'text'  => 'B级',
                            'count' => $bSiteLocationCount,
                            'radio' => ($managerInfoModel->siteLocationCount ? (int)($bSiteLocationCount / $managerInfoModel->siteLocationCount * 100) : 0) . '%',
                        ],
                    ]
                ],

            ]
        ];

    }


    /**
     * 开发经理详情列表
     * @param int $rmsUserId
     * @param int $type
     * @param int $pageNum
     * @param int $pageSize
     * @param string $grade
     * @param int $cityCode
     * @param int $developmentId
     * @return array
     */
    public static function taskDetail(int $rmsUserId, int $type, int $pageNum, int $pageSize, string $grade, int $cityCode, int $developmentId): array
    {
        switch ($type) {
            case 1: // 任务列表
                $data = SiteTaskService::list($pageNum, $pageSize, $rmsUserId, 0, $cityCode, 0, '', '', $grade, 0, '', '', '', $developmentId, '', '', '', '', '', '', '', '');
                break;
            case 2: // 跟进记录
                $paginator = CustomerDepartmentFollowUpRecordModel::query()
                    ->where('createdByUid', $developmentId)
                    ->orderByDesc('id')
                    ->with(['resourceRel', 'taskRel', 'clueRel'])
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

                $list = $paginator->map(function ($item) {

                    //资源
                    $files = [];
                    if (count($item->resourceRel)) {
                        $files = collect($item->resourceRel)->map(function ($file) {
                            return picturePath($file['url']);
                        });
                    }

                    // 线索内容
                    $clueContent = '-';
                    // 预计出铺时间
                    $preHaving = '-';
                    if (count($item->clueRel)) {
                        $clueContent = $item->clueRel->last()->content;
                        $preHaving   = Carbon::createFromTimestamp($item->clueRel->last()->preHaving)->toDateString();
                    }

                    return [
                        'wgName'      => '【' . (CustomerDepartmentTaskModel::GRADE_MAPPING[$item->taskRel->grade] ?? '-') . '】' . $item->taskRel->wgName,
                        'type'        => $item->type,
                        'typeStr'     => CustomerDepartmentFollowUpRecordModel::TYPE_MAPPING[$item->type] ?? '',
                        'method'      => $item->method,
                        'methodStr'   => CustomerDepartmentFollowUpRecordModel::METHOD_MAPPING[$item->method] ?? '',
                        'content'     => $item->content,
                        'time'        => $item->createdAt->toDateTimeString(),
                        'files'       => $files,
                        'clueContent' => $clueContent,
                        'preHaving'   => $preHaving,
                    ];
                });
                $data = [
                    'count'    => $paginator->total(),
                    'list'     => $list,
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                ];
                break;
            default:
                self::throwErr('列表类型不存在', 404);
        }

        return $data;
    }


    /**
     * 开发经理任务涉及区域
     * @param $userId
     * @return array
     */
    public static function involve($userId): array
    {
        $data = [];
        CustomerDepartmentTaskModel::query()
            ->where('assignId', $userId)
            ->get()
            ->each(function (CustomerDepartmentTaskModel $customerDepartmentTaskModel) use (&$data) {
                $cityName = explode('-', $customerDepartmentTaskModel->prefixAddress)[1] ?? null;
                if ($cityName != null) {
                    $data[$customerDepartmentTaskModel->cityCode] = [
                        'cityCode' => $customerDepartmentTaskModel->cityCode,
                        'cityName' => $cityName
                    ];
                }
            });
        return array_values($data);
    }

    public static function regionClassify() {}

}
